<?php

namespace app\index\controller;

use think\Model;
use think\Request;
use think\Db;
use app\index\model\User as UserModel;

class User extends BaseController
{
    // 用户列表页
    public function index()
    {
        // 班期信息
        $class = Db::name('class')
            ->field('class_name')
            ->order('class_name', 'DESC')
            ->select();
        // 在校生
        $total = Db::name('user')->sum('ustatus');
        $totalId = Db::name('user')->count('id');

        // 学员信息 + 查询条件
        $searchList = [];
        $searchName = input('get.name');
        $searchClass = input('get.class');
        if (!empty($searchName)) {
            $searchList['uname'] = ['like', "%$searchName%"];
        }
        if (!empty($searchClass)) {
            $searchList['uclass'] = $searchClass;
        }

        $user = new UserModel();
        $users = $user->userAll($searchList);
        $totalpage = count($users);

        return view('user/index',
            [
                'total' => $total,
                'totalpage' => $totalpage,
                'totalId' => $totalId,
                'class' => $class,
                'data' => $users
            ]
        );
    }


    // 用户列表页(带名字搜索)
    public function name($name)
    {
        // 班期信息
        $class = Db::name('class')
            ->field('class_name')
            ->order('class_name', 'DESC')
            ->select();
        // 在校生
        $total = Db::name('user')->sum('ustatus');
        $totalId = Db::name('user')->count('id');

        // 学员信息 + 查询条件
        $searchList = [];
        if (!empty($name)) {
            $searchList['uname'] = ['like', "%$name%"];
        }

        $user = new UserModel();
        $users = $user->userAll($searchList);
        $totalpage = count($users);

        return view('user/index',
            [
                'total' => $total,
                'totalpage' => $totalpage,
                'totalId' => $totalId,
                'class' => $class,
                'data' => $users
            ]
        );
    }


    // 查询指定用户的信息 和 积分信息
    public function read($id)
    {
        $row = Db::name('user')
            ->field(true)
            ->where('id', $id)
            ->find();

        if ($row) {
            $scoreList = Db::name('score')
                ->field(true)
                ->where('uid', $id)
                ->order('ctime', 'DESC')
                ->select();

            if ($scoreList == null) {
                $result = [
                    'code' => 200,
                    'status' => 'success',
                    'list' => $row,
                    'scoreList' => []
                ];
            } else {
                $result = [
                    'code' => 200,
                    'status' => 'success',
                    'list' => $row,
                    'scoreList' => $scoreList
                ];
            }
        } else {
            $result = ['code' => 4004, 'status' => 'danger', 'list' => '用户信息错误，请重试！'];
        }
        return $result;
    }


    // 新增页面
    public function create()
    {
        $class = Db::name('class')
            ->field('class_name')
            ->order('class_name', 'DESC')
            ->select();
        return view('user/create', ['class' => $class]);
    }


    // 保存新增学员信息
    public function save(Request $request)
    {
        $p = $request->post();
        $res = Db::name('user')->insertGetId($p);
        if ($res > 0) {
            $this->success('新增学员成功!', 'index/user/index', '', 1);
        } else {
            $this->error('新增学员失败,请重试!');
        }
    }


    // 校验学员姓名是否重复
    public function getname()
    {
        $name = input('get.name');
        $row = Db::name('user')
            ->field('id')
            ->where('uname', $name)
            ->find();
        if ($row == null) {
            $res = ['code' => 200, 'msg' => '通过！无重复姓名'];
        } else {
            $res = ['code' => 4004, 'msg' => '学员姓名有重复,请加班期作为标注'];
        }
        return $res;
    }


    // 删除学员 (未完成: 未关联积分的删除)
    public function delete($id)
    {
        $row = Db::name('user')->delete($id);
        if ($row) {
            $res = ['code' => 200, 'status' => 'success', 'msg' => '删除学员记录成功!'];
        } else {
            $res = ['code' => 4005, 'status' => 'warning', 'msg' => '删除学员记录失败,请重试!'];
        }
        return $res;
    }


    // 显示编辑资源表单页
    public function edit($id)
    {
        // 学员信息
        $row = Db::name('user')->field(true)->find($id);
        // 班期信息
        $class = Db::name('class')
            ->field('class_name')
            ->order('class_name', 'DESC')
            ->select();
        return view('user/edit', ['row' => $row, 'class' => $class]);
    }


    // 保存更新的资源
    public function update(Request $request, $id)
    {
        $put = $request->put();
        unset($put['_method']);
        $row = Db::name('user')
            ->field(['utel', 'usex', 'uinfo', 'umarks'])
            ->find($id);
        $diff = array_diff_assoc($put, $row);
        $res = Db::name('user')
            ->where('id', $id)
            ->update($diff);
        if ($res) {
            return $this->success('编辑完成!', 'index/user/index');
        } else {
            return $this->success('编辑失败，请重试!');
        }
    }

    // 修改学员在校状态
    public function status($id)
    {
        $oldS = input('put.status');
        $s = ($oldS == 1) ? 0 : 1;
        $row = Db::name('user')
            ->where('id', $id)
            ->update(['ustatus' => $s]);
        if ($row) {
            $res = [
                'code' => 200,
                'status' => 'success',
                'msg' => '修改 ' . $id . ' 学员状态成功!',
                'id' => $id,
                's' => $s
            ];
        } else {
            $res = [
                'code' => 4004,
                'status' => 'danger',
                'msg' => '状态修改失败,请重试!',
                'id' => $id,
                's' => $oldS
            ];
        }
        return $res;
    }

    // 转班操作
    public function shiftclass($id)
    {
        $row = Db::name('user')
            ->field(['uclass', 'uclassold'])
            ->find($id);
        $newclass = input('put.uclass');

        // 检查有无数据可更改
        if (empty($row)) {
            $res = ['code' => 4001, 'status' => 'danger', 'msg' => '缺少关键信息，操作终止!'];
        } else {
            // 检查班期是否被更改
            if ($row['uclass'] == $newclass) {
                $res = ['code' => 4005, 'status' => 'info', 'msg' => '转入班期，不得与当前所在班期相同！'];
            } else {
                // 检查有无 历史班期记录
                if ($row['uclassold'] == '') {
                    // 无历史,则直接写入转班
                    $data = [
                        'uclass' => $newclass,
                        'uclassold' => $row['uclass']
                    ];
                    $class = Db::name('user')->where('id', $id)->update($data);
                } else {
                    // 有历史,则拼接班级记录
                    $data = [
                        'uclass' => $newclass,
                        'uclassold' => $row['uclassold'] . '/' . $row['uclass']
                    ];
                    $class = Db::name('user')->where('id', $id)->update($data);
                }

                // 检查更改情况
                if ($class) {
                    $res = ['code' => 200, 'status' => 'success', 'msg' => '学员转班，操作完成!'];
                } else {
                    $res = ['code' => 4004, 'status' => 'danger', 'msg' => '转班失败，请重试!'];
                }
            }
        }
        return $res;
    }


    // 改写班期操作
    public function changeclass($id)
    {
        $row = Db::name('user')
            ->field(['uclass', 'uclassold'])
            ->find($id);
        $newclass = input('put.uclass');

        // 检查有无数据可更改
        if (empty($row)) {
            $res = ['code' => 4001, 'status' => 'danger', 'msg' => '缺少关键信息，操作终止!'];
        } else {
            // 检查班期是否被更改
            if ($row['uclass'] == $newclass) {
                $res = ['code' => 4005, 'status' => 'info', 'msg' => '改写班期，不得与当前所在班期相同！'];
            } else {
                $class = Db::name('user')->where('id', $id)->update(['uclass' => $newclass]);
                // 检查更改情况
                if ($class) {
                    $res = ['code' => 200, 'status' => 'success', 'msg' => '已给学员重新分配班期！'];
                } else {
                    $res = ['code' => 4004, 'status' => 'danger', 'msg' => '改写失败，请重试!'];
                }
            }
        }
        return $res;
    }


    // 隐藏管理页面
    public function hide()
    {
        if (session('admin.level') <= 0) {
            $this->redirect(url('index/index/index'));
            exit;
        }
        $adminuser = Db::name('adminuser')->field(true)->select();
        return view('user/hiden', ['adminuser' => $adminuser]);
    }


    // 重置入口密码
    public function resetpass()
    {
        $pass = md5(input('post.pass'));
        $row = Db::name('adminuser')
            ->where('name', null)
            ->update(['pwd' => $pass]);
        $this->redirect(url('index/index/index'));
    }


    // 设置管理员密码
    public function adminpass()
    {
        $id = input('post.id');
        $pass = md5(input('post.pass'));
        $row = Db::name('adminuser')
            ->where('id', $id)
            ->update(['pwd' => $pass]);
        $this->redirect(url('index/login/index'));
    }


    // 新增管理员页面
    public function createadmin()
    {
        return view('user/createadmin');
    }


    // 保存新增管理员
    public function saveadmin(Request $request)
    {
        $post = $request->post();
        foreach ($post as $val) {
            if ($val == '') {
                return $this->error('表单信息不完整!');
            }
        }
        $post['pwd'] = md5($post['pwd']);
        $row = Db::name('adminuser')->insertGetId($post);

        if ($row > 0) {
            return $this->success('新增管理员成功', 'index/user/hide');
        } else {
            return $this->error('新增管理员失败，请重试！');
        }
    }


    // 管理员个人页面
    public function admin($id)
    {
        $row = Db::name('adminuser')->where('id', $id)->find();
        return view('user/admin', ['row' => $row]);
    }
}
